package com.life.wd.service.Imp;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.life.wd.dto.SupplierDTO;
import com.life.wd.dto.SupplierUpdateDTO;
import com.life.wd.entity.Supplier;
import com.life.wd.exception.BusinessException;
import com.life.wd.mapper.SupplierMapper;
import com.life.wd.result.PageResult;
import com.life.wd.service.SupplierService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class SupplierServiceImp implements SupplierService {

    @Autowired
    private SupplierMapper supplierMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addSupplier(Supplier supplier) {
        // 检查邮箱是否已存在
        Supplier existSupplier = supplierMapper.getSupplierByEmail(supplier.getEmail());
        if (existSupplier != null) {
            throw new BusinessException("401","该邮箱已被其他供应商使用");
        }

        // 设置创建时间和更新时间
        supplier.setCreatedAt(new Date());
        supplier.setUpdatedAt(new Date());

        return supplierMapper.insertSupplier(supplier);
    }

    @Override
    public PageResult listSupplier(SupplierDTO supplier) {
        PageHelper.startPage(supplier.getPage(),supplier.getPageSize());
        Page<Supplier> suppliers = supplierMapper.listSupplier(supplier);
        return new PageResult(suppliers.getTotal(),suppliers.getResult());
    }

    @Override
    public void updateSupplier(Integer id, SupplierUpdateDTO updateDTO) {
        Supplier supplier = supplierMapper.selectById(id);
        if (supplier == null) {
            throw new BusinessException("401","供应商不存在");
        }

        // 检查新邮箱是否已存在(如果修改了邮箱)
        if (updateDTO.getEmail() != null && !updateDTO.getEmail().equals(supplier.getEmail())) {
            if (supplierMapper.existsByEmail(updateDTO.getEmail())) {
                throw new BusinessException("401","该邮箱已被其他供应商使用");
            }
        }

        // 动态更新字段
        BeanUtils.copyProperties(updateDTO, supplier);
        supplier.setUpdatedAt(new Date()); // 更新时间戳

        supplierMapper.updateById(supplier);
    }

    @Override
    public void deleteSupplier(Integer id) {
        Supplier supplier = supplierMapper.selectById(id);
        if (supplier == null) {
            throw new BusinessException("401","供应商不存在");
        }
        supplierMapper.deleteById(id);
    }


    @Override
    public void validateSupplierExists(Integer supplierId) {
        if (supplierId == null) {
            throw new IllegalArgumentException("供应商ID不能为空");
        }
        Supplier supplier = supplierMapper.getById(supplierId);
        if (supplier == null) {
            throw new BusinessException("401",
                    "供应商不存在，ID: " + supplierId);
        }
    }
}